package conchmusic.conchmusicclient.mainUi;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;


import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.activity.DownloadActivity;
import conchmusic.conchmusicclient.activity.LocalMusicActivity;
import conchmusic.conchmusicclient.activity.OnlineSearchActivity;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.SongList;
import conchmusic.conchmusicclient.pojo.UpdatedData;
import conchmusic.conchmusicclient.popupWindow.SongListPopu;
import conchmusic.conchmusicclient.util.CreateSlistCommand;
import conchmusic.conchmusicclient.util.DeleteSlistCommand;
import conchmusic.conchmusicclient.util.FindAllSlistCommand;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.util.Invoker;
import conchmusic.conchmusicclient.util.JsonBuilder;
import conchmusic.conchmusicclient.util.JsonParser;
import conchmusic.conchmusicclient.util.ModifySlistCommand;
import conchmusic.conchmusicclient.view.PlayBar;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private ArrayList<SongList> songLists;

    public static Handler getHandler() {
        return handler;
    }

    private static Handler handler;
    private Handler handler1;

    public static Popup getPopup() {
        return popup;
    }

    private static Popup popup;
    private MediaPlayer mp;

    public static SurePopup getSp() {
        return sp;
    }

    private MyDBHelp myDBHelp;
    private static SurePopup sp;
    private Invoker invoker;
    private CreateSlistCommand createSlistCommand;
    private DeleteSlistCommand deleteSlistCommand;
    private ModifySlistCommand modifySlistCommand;
    private FindAllSlistCommand findAllSlistCommand;
    private JsonParser jp;
    private JsonBuilder jb;
    private int uid;
    private TextView nameShow;

    public static UpdatePopup getUp() {
        return up;
    }

    private ClientControl cc;
    private static UpdatePopup up;
    private InitPlayBar initPlayBar;

    private  PlayBar playBar;

    @Override
    protected void onResume() {
        super.onResume();
        initPlayBar=new InitPlayBar(playBar,this);
        initPlayBar.initPlaybar();
        playBar.startMsgReceiver();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "创建新歌单", Snackbar.LENGTH_LONG)
                        .setAction("+", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
//                                toastshow("一一一");
                                showEditDialog(view);
                            }
                        }).show();
            }
        });
//playBar.startMsgReceiver();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        playBar=(PlayBar)findViewById(R.id.main_playbar);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View navView = navigationView.getHeaderView(0);
        nameShow = (TextView) navView.findViewById(R.id.userNameShow);
        Log.i("main111", "onCreate: " + nameShow.getId());
        myDBHelp = new MyDBHelp(this, "demon", null, 1);
        cc = new ClientControl(myDBHelp);
        songLists = new ArrayList<SongList>();
        jb = new JsonBuilder();
        jp = new JsonParser();
//        songLists.add();
        invoker = new Invoker();


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                //各种更新界面
                String shows = msg.getData().getString("show");
                    toastshow2(shows);
                listIntent();

            }
        };
        sp = new SurePopup(this, R.style.AppTheme, onClickListener2);
//        up = new UpdatePopup(this, R.style.AppTheme, onClickListener3);
        updatePopup();
        if (cc.Login() != null) {
            uid = cc.Login().getUserId();
            Log.i("main139", "onCreate: " + cc.Login().getUserName());
            nameShow.setText(cc.Login().getUserName());
            listIntent();//判断是否登录

            Log.i("main146", "onCreate: " + uid);
        } else {
            toastshow2("游客模式");
        }
    }


    public void updatePopup() {
        up = new UpdatePopup(this, R.style.AppTheme, onClickListener3);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();


        if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //跳转系列
    public void regist(MenuItem item) {
//        跳转到注册页面
        jumpActivity(RegistActivity.class, "nothing");
    }

    public void search(MenuItem item) {
        //搜索框
        Intent intent = new Intent();
        intent.setClass(this, OnlineSearchActivity.class);
        startActivityForResult(intent, 1);
    }

    public void playActivity(View view) {
        //跳转到播放页
        Intent intent = new Intent();
//        intent.setClass(this, playImageActivity.class);
        startActivityForResult(intent, 1);
    }

    public void localMusic(View view) {
//        jumpActivity(getClass(),"1");
        Intent localInent = new Intent(MainActivity.this, LocalMusicActivity.class);
        startActivity(localInent);
    }

    public void feedback(MenuItem item) {
//        假的分享功能
        Intent localInent = new Intent(MainActivity.this, SkinActivity.class);
        Log.i("Main localMusic239","localMusic");
        startActivity(localInent);

    }
public void skin(){
findViewById(R.id.drawer_layout).setBackgroundColor(Color.YELLOW);
}
    public void logout(MenuItem item) {
//        登出
        if (cc.Login() != null) {
            cc.logout(uid);
            toastshow2("已注销");
            jumpActivity(LoginActivity.class, "nothing");
        } else {
            toastshow2("游客不可以注销的哦");
        }
    }

    public void login(MenuItem item) {
//        跳转到登陆页面
        jumpActivity(LoginActivity.class, "nothing");
    }

    public void listIntent() {
//从数据库里面读songlists
        songLists = (ArrayList<SongList>) cc.getSongLists(uid);
        ListView lv = (ListView) findViewById(R.id.songList);
        songListAdpater alAdpater = new songListAdpater(MainActivity.this, songLists);
        lv.setAdapter(alAdpater);
    }

    public void jumpActivity(Class c, String s) {
        Intent intent = new Intent();
        intent.putExtra("send", s);
        intent.setClass(this, c);
        //跳转到歌单页面，并发送歌单名字出去在数据库匹配一下，再显示到那个activity。
        startActivityForResult(intent, 1);
    }

    public void showEditDialog(View view) {
        popup = new Popup(this, R.style.AppTheme, onClickListener);
        popup.show();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.createSongList:
                    String songListName = popup.songListname.getText().toString();
                    int a=0;
                    for(int i=0;i<songLists.size();i++){
                        if(songListName.equals(songLists.get(i).getSongListName())){
                            a=1;
                        }
                    }
                    if (songListName.equals("") || songListName.equals(null) || songListName == null || songListName.equals(" ")) {
                        toastshow2("请输入名称");
                    } else if(a==1){toastshow2("不可以重复创建哦");} else {

                        //发送uid和sonlistname给服务器，然后得到成功响应后，执行更新操作。当然handle之

//                        songLists.add(sl);
                        //发送用户id和歌单名创建，得到成功就更新操作.......判断登录状态,获取id

                        SongList sl = new SongList();
                        sl.setSongListName(songListName);
                        sl.setUserId(uid);
                        try {
                            String slistJson = jb.buildSongList(sl);
                            Log.i("main299", "onClick: "+slistJson);
                            CreateSlistCommand createSlistCommand = new CreateSlistCommand(getResources(), slistJson);
                            invoker.setTransferCommand(createSlistCommand);
                            new Thread() {
                                @Override
                                public void run() {
                                    String jsonRecive = invoker.action();
                                    Log.i("main306", "run: "+jsonRecive);
                                    try {
                                        String type = jp.typeOf(jsonRecive);
                                        if (type.equals("invalidInfo")) {
                                            toastshow("网络异常，请重试");
                                        } else {
                                            updateSongList("创建成功");//user id

                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        System.out.println(songListName + "——");

                        popup.cancel();//两个好像都可以不知道区别在哪里哈哈哈
                        break;
                    }
            }
        }
    };

    private View.OnClickListener onClickListener2 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.sureDelete:

                    int j = SongListPopu.getPos();
                    int i = songLists.get(j).getSongListId();
                    deleteSlistCommand = new DeleteSlistCommand(getResources(), i);
                    invoker.setTransferCommand(deleteSlistCommand);
                    new Thread() {
                        @Override
                        public void run() {
                            String jsonRecive = invoker.action();
                            try {
                                String type = jp.typeOf(jsonRecive);
                                if (type.equals("invalidInfo")) {
                                    toastshow("网络异常，请重试");
                                } else {
                                    updateSongList("删除成功");//user id
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                    sp.cancel();
                    break;
                case R.id.notSureDelete:

                    sp.cancel();
                    break;
            }
        }
    };


    @Override
    protected void onPause() {
        playBar.closeMsgReceiver();
        super.onPause();
    }

    private View.OnClickListener onClickListener3 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.songListUpdate:
                    int j = SongListPopu.getPos();

                    String songListNameUpdate = up.songListNameUpdate.getText().toString();
                    String songListDescripe = up.songListDescripe.getText().toString();
                    int slistId = songLists.get(j).getSongListId();
                    Log.i("main376", "onClick: " + j);
                    SongList sl = new SongList();
                    sl.setDescription(songListDescripe);
                    sl.setSongListName(songListNameUpdate);
                    sl.setSongListId(slistId);
                    try {
                        String jsonSlist = jb.buildSongList(sl);
                        modifySlistCommand = new ModifySlistCommand(getResources(), jsonSlist);
                        invoker.setTransferCommand(modifySlistCommand);
                        new Thread() {
                            @Override
                            public void run() {
                                String jsonRecive = invoker.action();
                                try {
                                    String type = jp.typeOf(jsonRecive);
                                    if (type.equals("invalidInfo")) {
                                        toastshow("网络异常，请重试");
                                    } else {
                                        updateSongList("修改成功");//user id
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    up.cancel();//两个好像都可以不知道区别在哪里哈哈哈
                    break;
            }
        }

    };

    public void updateSongList(final String ss) {
        findAllSlistCommand = new FindAllSlistCommand(getResources(), uid);
        invoker.setTransferCommand(findAllSlistCommand);
        new Thread() {
            @Override
            public void run() {
                String jsonRecive = invoker.action();
                try {
                    UpdatedData ud = jp.parseUpdatedData(jsonRecive);
                    cc.update(ud);

                    handlesend("show", ss);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    public void playMusic(View view) {
        mp = new MediaPlayer();
        Log.i("main433", "playMusic: ");
        String songUrl = "http://119.29.88.206:80/TestMusic/music/zhangda.mp3";
        try {
            mp.setDataSource(songUrl);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pauseMusic(View view) {
        mp.pause();
    }

    public void toastshow(String story) {
        getMainLooper().prepare();
        Toast toast = Toast.makeText(getApplicationContext(), story, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        LinearLayout toastView = (LinearLayout) toast.getView();
        ImageView imageCodeProject = new ImageView(getApplicationContext());
        imageCodeProject.setImageResource(R.mipmap.ic_launcher);
        toastView.addView(imageCodeProject, 0);
        toast.show();
        getMainLooper().loop();

    }
    public void toastshow2(String story) {

        Toast toast = Toast.makeText(getApplicationContext(), story, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        LinearLayout toastView = (LinearLayout) toast.getView();
        ImageView imageCodeProject = new ImageView(getApplicationContext());
        imageCodeProject.setImageResource(R.mipmap.ic_launcher);
        toastView.addView(imageCodeProject, 0);
        toast.show();


    }
    public void handlesend(String key, String val) {//给handler传消息的函数
        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString(key, val);
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    public void handlesend1(String key, String val) {//给handler传消息的函数
        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString(key, val);
        msg.setData(bundle);
        handler1.sendMessage(msg);
    }

    public void downloadMusic(View view) {
        Intent downloadIntent = new Intent(MainActivity.this, DownloadActivity.class);

        //传入是否登录
        startActivity(downloadIntent);
    }

    public void recongnize(MenuItem item) {
//        听歌识曲
        Intent localInent = new Intent(MainActivity.this, RecognizeActivity.class);
        startActivity(localInent);
    }

    public void share(MenuItem item) {
        Intent localInent = new Intent(MainActivity.this, ContactActivity.class);
        startActivity(localInent);
    }
}
